<template>
  <div class="user-container">
    <el-card class="user-card">
      <div slot="header" class="card-header">
        <span>用户管理</span>
        <el-button
          type="primary"
          size="small"
          @click="handleAdd">
          添加用户
        </el-button>
      </div>

      <!-- 搜索和过滤 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="用户号">
            <el-input
              v-model="filterForm.userId"
              placeholder="请输入用户号"
              clearable
              @clear="handleFilter">
            </el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
              v-model="filterForm.name"
              placeholder="请输入姓名"
              clearable
              @clear="handleFilter">
            </el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-select
              v-model="filterForm.role"
              placeholder="请选择角色"
              clearable
              @clear="handleFilter">
              <el-option label="学生" value="student"></el-option>
              <el-option label="教师" value="teacher"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学校">
            <el-input
              v-model="filterForm.universityName"
              placeholder="请输入学校"
              clearable
              @clear="handleFilter">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%">
        <el-table-column
          prop="userId"
          label="用户号"
          width="120">
        </el-table-column>

        <el-table-column
          prop="name"
          label="姓名"
          width="120">
        </el-table-column>

        <el-table-column
          prop="role"
          label="角色"
          width="100">
          <template slot-scope="scope">
            {{ scope.row.role === 'student' ? '学生' : '教师' }}
          </template>
        </el-table-column>

        <el-table-column
          prop="universityName"
          label="学校"
          width="180">
        </el-table-column>

        <el-table-column
          prop="collegeName"
          label="学院"
          width="180">
        </el-table-column>

        <el-table-column
          prop="majorName"
          label="专业"
          width="180">
        </el-table-column>

        <el-table-column
          prop="grade"
          label="年级"
          width="100">
        </el-table-column>

        <el-table-column
          prop="classId"
          label="班级"
          width="100">
        </el-table-column>

        <el-table-column
          label="操作"
          fixed="right"
          width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <!-- 添加/编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="50%">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px">
          <el-form-item label="用户号" prop="userId">
            <el-input v-model="form.userId"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" placeholder="请选择角色">
              <el-option label="学生" value="student"></el-option>
              <el-option label="教师" value="teacher"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="!form.id">
            <el-input v-model="form.password" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item label="学校" prop="universityName">
            <el-input v-model="form.universityName"></el-input>
          </el-form-item>
          <el-form-item label="学院" prop="collegeName">
            <el-input v-model="form.collegeName"></el-input>
          </el-form-item>
          <el-form-item label="专业" prop="majorName">
            <el-input v-model="form.majorName"></el-input>
          </el-form-item>
          <el-form-item :label="form.role === 'student' ? '* 年级' : '年级'" prop="grade" v-if="form.role !== 'admin'">
            <el-input v-model="form.grade"></el-input>
          </el-form-item>
          <el-form-item :label="form.role === 'student' ? '* 班级 ' : '班级'" prop="classId" v-if="form.role !== 'admin'">
            <el-input v-model="form.classId"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { userApi } from '@/api'

export default {
  name: 'UserList',
  data() {
    return {
      loading: false,
      saving: false,
      users: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      filterForm: {
        userId: '',
        name: '',
        role: '',
        universityName: ''
      },
      form: {
        id: null,
        userId: '',
        name: '',
        role: '',
        password: '',
        universityName: '',
        collegeName: '',
        majorName: '',
        grade: '',
        classId: ''
      },
      rules: {
        userId: [
          { required: true, message: '请输入用户号', trigger: 'blur' },
          { validator: this.validateUserId, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
        ],
        universityName: [
          { required: true, message: '请输入学校名称', trigger: 'blur' }
        ],
        collegeName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' }
        ],
        majorName: [
          { required: true, message: '请输入专业名称', trigger: 'blur' }
        ],
        grade: [
          { validator: this.validateStudentField, trigger: 'blur' }
        ],
        classId: [
          { validator: this.validateStudentField, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchUsers()
  },
  watch: {
    'form.role': function(newRole) {
      // 当角色变化时，重新验证年级和班级字段
      if (this.$refs.form) {
        this.$nextTick(() => {
          this.$refs.form.validateField('grade')
          this.$refs.form.validateField('classId')
        })
      }
    }
  },
  methods: {
    async fetchUsers() {
      try {
        this.loading = true
        const queryParams = {
          ...this.filterForm,
          page: this.currentPage,
          size: this.pageSize
        }
        
        console.log('查询参数:', queryParams) // 添加日志
        
        const res = await userApi.list(queryParams)
        
        console.log('查询结果:', res) // 添加日志
        
        if (res.code === 200 && res.data) {
          // 检查返回的数据结构
          if (Array.isArray(res.data.list)) {
            this.users = res.data.list.filter(user => user.role !== 'admin')
          } else if (Array.isArray(res.data.records)) {
            this.users = res.data.records.filter(user => user.role !== 'admin')
          } else {
            console.error('意外的数据结构:', res.data)
            this.users = []
          }
          this.total = res.data.total || 0
        } else {
          this.$message.error(res.msg || '获取用户列表失败')
          this.users = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取用户列表错误：', error)
        this.$message.error('获取用户列表失败')
        this.users = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchUsers()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchUsers()
    },
    handleFilter() {
      this.currentPage = 1
      this.fetchUsers()
    },
    resetFilter() {
      this.filterForm = {
        userId: '',
        name: '',
        role: '',
        universityName: ''
      }
      this.handleFilter()
    },
    handleAdd() {
      this.dialogTitle = '添加用户'
      this.form = {
        userId: '',
        name: '',
        role: '',
        password: '',
        universityName: '',
        collegeName: '',
        majorName: '',
        grade: '',
        classId: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.form = { ...row }
      this.dialogVisible = true
    },
    validateUserId(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入用户号'));
        return;
      }
      if (this.form.role === 'admin') {
        if (!/^\d{1,5}$/.test(value)) {
          callback(new Error('管理员用户号必须是1-5位数字'));
        }
      } else if (this.form.role === 'teacher') {
        if (!/^\d{6,9}$/.test(value)) {
          callback(new Error('教师用户号必须是6-9位数字'));
        }
      } else if (this.form.role === 'student') {
        if (!/^\d{10,}$/.test(value)) {
          callback(new Error('学生用户号必须是至少10位数字'));
        }
      }
      callback();
    },
    validateStudentField(rule, value, callback) {
      if (this.form.role === 'student' && !value) {
        callback(new Error(`请输入${rule.field === 'grade' ? '年级' : '班级'}`));
      } else {
        callback();
      }
    },
    async handleSave() {
      try {
        await this.$refs.form.validate()
        
        console.log('表单验证通过，准备保存数据:', this.form);
        
        // 根据角色验证必填字段
        if (this.form.role === 'student') {
          if (!this.form.universityName || !this.form.collegeName || 
              !this.form.majorName || !this.form.grade || !this.form.classId) {
            this.$message.error('学生用户必须填写完整的学校、学院、专业、年级和班级信息');
            return;
          }
        } else if (this.form.role === 'teacher') {
          if (!this.form.universityName || !this.form.collegeName || !this.form.majorName) {
            this.$message.error('教师用户必须填写完整的学校、学院和专业信息');
            return;
          }
        }
        
        this.saving = true
        let res;
        
        // 构造要发送的数据，根据角色进行处理
        const userData = {
          userId: this.form.userId,
          name: this.form.name,
          role: this.form.role,
          universityName: this.form.universityName,
          collegeName: this.form.collegeName,
          majorName: this.form.majorName,
          // 年级字段，如果为空则发送null
          grade: this.form.grade || null,
          // 班级字段，如果为空则发送null
          classId: this.form.classId || null
        };
        
        // 只有在创建新用户时才添加密码字段
        if (this.dialogTitle !== '编辑用户') {
          userData.password = this.form.password;
        }
        
        console.log('准备发送的用户数据:', userData);

        try {
          if (this.form.userId && this.dialogTitle === '编辑用户') {
            // 更新用户
            console.log(`正在更新用户 ${userData.userId}`);
            res = await userApi.update(userData.userId, userData);
          } else {
            // 创建用户
            console.log('正在创建新用户');
            res = await userApi.create(userData);
          }
          
          console.log('服务器响应:', res);
          
          if (res.code === 200) {
            this.$message.success(this.dialogTitle === '编辑用户' ? '更新成功' : '添加成功')
            this.dialogVisible = false
            this.fetchUsers()
          } else {
            let errorMsg = res.message || (this.dialogTitle === '编辑用户' ? '更新失败' : '添加失败');
            // 如果有更详细的错误信息，显示它
            if (res.data && typeof res.data === 'string') {
              errorMsg += ': ' + res.data;
            }
            this.$message.error(errorMsg);
            console.error('服务器返回错误:', res);
          }
        } catch (apiError) {
          console.error('API调用错误:', apiError);
          // 尝试提取更多错误信息
          let errorMessage = apiError.message || '服务器错误';
          if (apiError.response && apiError.response.data) {
            const responseData = apiError.response.data;
            if (responseData.message) {
              errorMessage = responseData.message;
            } else if (typeof responseData === 'string') {
              errorMessage = responseData;
            }
          }
          this.$message.error(`${this.dialogTitle === '编辑用户' ? '更新' : '创建'}失败: ${errorMessage}`);
        }
      } catch (error) {
        console.error('保存用户错误：', error);
        this.$message.error('保存失败，请检查输入信息');
      } finally {
        this.saving = false;
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户，是否继续？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await userApi.delete(row.userId)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.fetchUsers()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          console.error('删除用户错误：', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.user-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 